package org.xdq.springcloud.demo20191222.zuul;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.xdq.base.Constants;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
@Component
public class AuthenticationFilter extends ZuulFilter{
	
	private static final Logger LOG = LoggerFactory.getLogger(AuthenticationFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }
 
    @Override
    public int filterOrder() {
        return 0;
    }
 
   
	public boolean shouldFilter() {
		// TODO Auto-generated method stub
		return false;
	}

	public Object run() throws ZuulException {
		RequestContext currentContext = RequestContext.getCurrentContext();

        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();
        
        String path = request.getServletPath();
        
        LOG.debug("--------------------"+path+"-----------------------"); 
        
        
        if(path.startsWith("/safty-login")) {
        	return null;
        }
        
        HttpSession session = request.getSession();
        Object currUser = session.getAttribute(Constants.SESSION_ATTR_CURR_USER);

		if (currUser == null) {

			try {
				response.setContentType("application/json;charset=UTF-8");
				PrintWriter out = response.getWriter();
				
				out.print("{\"logined\":false}");
				
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			throw new RuntimeException();
		}
        
        
        return null;
	}

}
